import java.util.Stack;

/**
 * @description:
 * @Author: wuzhenbin
 * @CreateTime: 2025/2/16
 */
public class leetcode_394 {
    public static void main(String[] args) {

    }

    public String decodeString(String s) {
        // 使用栈来存储字符串和数字
        Stack<Integer> counts = new Stack<>();
        Stack<StringBuilder> result = new Stack<>();
        StringBuilder currentString = new StringBuilder();
        int currentNum = 0;

        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                // 如果是数字，更新当前的数字
                currentNum = currentNum * 10 + (c - '0');
            } else if (c == '[') {
                // 如果是左括号，将当前数字和字符串压入栈
                counts.push(currentNum);
                result.push(currentString);
                // 重置当前数字和当前字符串
                currentNum = 0;
                currentString = new StringBuilder();
            } else if (c == ']') {
                // 如果是右括号，弹出栈中的数字和字符串
                StringBuilder prevString = result.pop();
                int repeatCount = counts.pop();
                // 重复当前字符串并拼接到之前的字符串上
                for (int i = 0; i < repeatCount; i++) {
                    prevString.append(currentString);
                }
                currentString = prevString;
            } else {
                // 否则是字母，直接添加到当前字符串中
                currentString.append(c);
            }
        }
        return currentString.toString();
    }
}
